package com.google.code.whitetask;

import static com.google.code.whitetask.Result.*;

public class RetryTask implements Task {
  private Result result;
  private int maximumCount;

  public RetryTask(Result result, int count) {
    super();
    this.result = result;
    this.maximumCount = count;
  }
  
  public Result execute(Context context) {
    if (context.isThereLastTaskBeingRan() == false) {
      throw new IllegalStateException(
          "If you are using the notation as 'ifLastResult...' on DSL,"
              + "you should check whether there is a previous task " + ""
              + "which is executed prior to using the notation.");
    }

    if (context.getLastResult() != result) {
      return SUCCESS;
    }
    
    for (int i = 0; i < maximumCount; i++) {
      Result eachResult = context.getLastTask().execute(context);

      if (eachResult != result) {
        return SUCCESS;
      }
    }
    
    return FAILURE;
  }
}
